import http from 'http';
import httpProxy from 'http-proxy';
import fse from 'fs-extra';
import jsonc from 'jsonc-parser';
import chalk from 'chalk';
import { getIpByInternal } from './ip.js'

let configFile = fse.readFileSync('./config.jsonc');
let rootNode = jsonc.parseTree(configFile.toString("utf-8"));
let target = jsonc.findNodeAtLocation(rootNode, ['target']).value;
let listenPort = jsonc.findNodeAtLocation(rootNode, ['listen-port']).value;


let proxy_rule = httpProxy.createProxyServer();

proxy_rule.on('error', function (err, req, res) {
    console.log(err);
    res.end();
});

// 配置代理规则
let proxy_server = http.createServer(function (req, res) {
    proxy_rule.web(req, res, {
        changeOrigin: true, // 如果接口跨域，需要进行这个参数配置为true
        headers: { host: '127.0.0.1', 'X-Forwarded-For': '127.0.0.1' }, // read https://github.com/chimurai/http-proxy-middleware#options
        target: target
    });
});

// 新启监听端口 -- 外部机器访问此端口
proxy_server.listen(listenPort, function () {
    console.log(`Reverse Proxy is running on:`);
    getIpByInternal().forEach((ip) => {
        let address = chalk.bold.hex('#ffa400')(`${ip}:${listenPort}`);
        console.log(`  ${address} `);
    })
});
